import {toArray} from '@rxTools/ext/array'

var index = 11111,
    noop=function(){};
var store,
  globalConfig={};
function mask(component,config) {
  var resolve,
    reject,
    promise = new Promise((res, rej) => {
      resolve = res;
      reject = rej;
    })
  var el = document.createElement('div');
  el.style.position = "fixed";
  el.style.top = 0;
  el.style.left = 0;
  el.style.right = 0;
  el.style.bottom = 0;
  el.style.zIndex = index++;
  el.style.backgroundColor='rgba(0,0,0,0.5)';
  el.style.overflow='auto';

  var div = document.createElement('div')
  document.body.appendChild(el);
  el.appendChild(div)
  var vueClass = Vue.extend(component);

  var vm = new vueClass({
    el: div,
    store,
    ...globalConfig,
    propsData: config
  });
  var endFn=function(){
    el.remove();
    index--;
  }
  vm.$on('resolve', function(){
    /* promise 只接收一个参数 */
    resolve.apply(null,toArray(arguments));
    endFn();
  })
  vm.$on('reject', function(){
    /* promise 只接收一个参数 */
    reject.apply(null,toArray(arguments));
    endFn();
  })
  var old=window.onpopstate;
  window.onpopstate=function(){
    endFn();
    reject('浏览器onpopstate事件，关闭弹窗');
    if(old){
      old.apply(window,toArray(arguments));
    }
  }
  promise.$rxClose=(arg)=>{
    resolve.apply(null,toArray(arguments));
    endFn();
  }
  return promise;
}
//TODO ESC 退出支持
/*
设置仓储
 */
mask.setStore = function (val) {
  store = val;
}
/* 全局配置生命周期事件 */
// mask.config=function(config){
//   globalConfig=config
// }
export default mask
